<template>
  <div class="delivered-page">
    <!-- 页面标题与搜索区 -->
    <div class="page-header">
      <div class="search-container">
        <!-- 移除用户ID搜索框（因为隐藏了seekerUserId） -->
        <el-input
          v-model="searchName"
          placeholder="搜索姓名/职位"
          size="small"
          style="width: 220px"
        >
          <template #append>
            <el-button
              icon="el-icon-search"
              size="small"
              @click="searchByKeyword"
            ></el-button>
          </template>
        </el-input>
      </div>
    </div>

    <!-- 数据表格 -->
    <el-card class="mt-4">
      <el-table
        :data="tableData"
        border
        stripe
        :loading="loading"
        style="width: 100%"
      >
        <!-- 求职者信息 -->
        <el-table-column label="求职者信息">
          <template #default="scope">
            <div class="user-info">
              <el-avatar
                :src="scope.row.avatar || defaultAvatar"
                size="50"
                class="avatar"
              ></el-avatar>
              <div class="user-info-detail">
                <div class="name">{{ scope.row.name || "未知" }}</div>
                <div class="phone">
                  <span v-if="scope.row.phone">{{
                    maskPhone(scope.row.phone)
                  }}</span>
                  <span v-else>未填写</span>
                </div>
              </div>
            </div>
          </template>
        </el-table-column>

        <!-- 学历 -->
        <el-table-column
          prop="education"
          label="学历"
          width="100"
          align="center"
        >
          <template #default="scope">
            <el-tag
              size="small"
              :type="getEducationTagType(scope.row.education)"
            >
              {{ formatEducation(scope.row.education) }}
            </el-tag>
          </template>
        </el-table-column>

        <!-- 期望信息 -->
        <el-table-column label="期望信息" width="250">
          <template #default="scope">
            <div class="expected-item">
              行业：{{ scope.row.expectedIndustry || "未填写" }}
            </div>
            <div class="expected-item">
              岗位：{{ scope.row.expectedPosition || "未填写" }}
            </div>
            <div class="expected-item">
              薪资：{{ formatSalary(scope.row.expectedSalary) }}
            </div>
          </template>
        </el-table-column>

        <!-- 申请职位 -->
        <el-table-column label="申请职位" width="200">
          <template #default="scope">
            <div
              class="position-name"
              :class="{ expired: isPositionExpired(scope.row.endAt) }"
            >
              {{ scope.row.positionName || "未知职位" }}
              <el-tag
                size="mini"
                type="danger"
                v-if="isPositionExpired(scope.row.endAt)"
                >已过期</el-tag
              >
            </div>
          </template>
        </el-table-column>

        <!-- 时间信息 -->
        <el-table-column label="时间信息" width="220">
          <template #default="scope">
            <div class="time-item">
              投递：{{ formatDate(scope.row.createdAt) }}
            </div>
            <div class="time-item">
              更新：{{ formatDate(scope.row.updatedAt) }}
            </div>
            <div class="time-item" v-if="scope.row.endAt">
              到期：{{ formatDate(scope.row.endAt) }}
            </div>
          </template>
        </el-table-column>

        <!-- 操作 -->
        <el-table-column label="操作" width="200" align="center">
          <template #default="scope">
            <el-button
              size="mini"
              type="primary"
              @click="handleInvite(scope.row.id)"
              :disabled="isPositionExpired(scope.row.endAt)"
              :class="{ 'disabled-btn': isPositionExpired(scope.row.endAt) }"
              class="mr-2"
            >
              邀约面试
            </el-button>
            <el-button
              size="mini"
              type="info"
              @click="handleViewResume(scope.row)"
            >
              查看简历
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 30]"
          :page-size="pageSize"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
        ></el-pagination>
      </div>
    </el-card>
    <resume :userId="currentid" :visible.sync="open"></resume>
  </div>
</template>

<script>
import {
  getDeliverList,
  interview,
} from "@/api/recuriter/applicationManagement";
import resume from "../compoment/resume.vue";
export default {
  components: { resume },
  data() {
    return {
      tableData: [],
      total: 0,
      currentPage: 1,
      pageSize: 10,
      loading: false,
      defaultAvatar:
        "https://cube.elemecdn.com/3/7c/3ea6beec6434fd293262dd8b1e36jpeg.jpeg",
      currentid: 1,
      open: false,
      // 移除searchId（因为不再通过用户ID搜索）
      searchName: "",
      resumeDialogVisible: false,
      currentResume: {},
      inviteRules: {
        interviewTime: [
          { required: true, message: "请选择面试时间", trigger: "blur" },
        ],
        location: [
          { required: true, message: "请填写面试地点", trigger: "blur" },
        ],
      },
      educationMap: {
        UNDERGRADUATE: "本科",
        MASTER: "硕士",
        DOCTOR: "博士",
        HIGH_SCHOOL: "高中",
        VOCATIONAL: "专科",
        JUNIOR_HIGH: "初中",
        PRIMARY_SCHOOL: "小学",
      },
    };
  },
  created() {
    this.fetchData();
  },
  methods: {
    async fetchData() {
      this.loading = true;
      try {
        const res = await getDeliverList();
        if (res.data.code === 201) {
          this.tableData = res.data.data;
          this.total = this.tableData.length;
          this.loading = false;
        } else {
          this.$message.error("加载失败");
        }
      } catch (error) {
        console.log("获取列表失败", error);
      }
    },

    searchByKeyword() {
      if (!this.searchName) {
        this.fetchData();
        return;
      }
      const keyword = this.searchName.trim().toLowerCase();
      this.loading = true;
      setTimeout(() => {
        this.tableData = this.tableData.filter(
          (item) =>
            (item.name && item.name.toLowerCase().includes(keyword)) ||
            (item.positionName &&
              item.positionName.toLowerCase().includes(keyword)) ||
            (item.expectedPosition &&
              item.expectedPosition.toLowerCase().includes(keyword))
        );
        this.total = this.tableData.length;
        this.currentPage = 1;
        this.loading = false;
      }, 300);
    },

    handleCurrentChange(page) {
      this.currentPage = page;
    },
    handleSizeChange(size) {
      this.pageSize = size;
      this.currentPage = 1;
    },

    async handleInvite(id) {
      try {
        let res = await interview(id);
        this.$store.commit("seeker/SET_TOKEN", res.data.data);
      } catch (error) {
        this.$message.error("邀约面试失败,请稍后重试");
      }
    },

    handleViewResume(row) {
      this.currentid = row.seekerUserId;
      this.open = true;
    },

    formatEducation(education) {
      return this.educationMap[education] || "未知";
    },

    getEducationTagType(education) {
      const typeMap = {
        UNDERGRADUATE: "primary",
        MASTER: "success",
        DOCTOR: "warning",
        VOCATIONAL: "info",
        HIGH_SCHOOL: "info",
        JUNIOR_HIGH: "info",
        PRIMARY_SCHOOL: "info",
      };
      return typeMap[education] || "default";
    },

    formatSalary(salary) {
      if (!salary || salary <= 0) return "未填写";
      return `${(salary / 10000).toFixed(1)}k/月`;
    },

    formatDate(dateStr) {
      if (!dateStr) return "未知";
      const date = new Date(dateStr);
      return date.toLocaleString("zh-CN", {
        year: "numeric",
        month: "2-digit",
        day: "2-digit",
        hour: "2-digit",
        minute: "2-digit",
      });
    },

    maskPhone(phone) {
      if (!phone) return "";
      return phone.replace(/(\d{3})(\d{4})(\d{4})/, "$1****$3");
    },

    isPositionExpired(endAt) {
      if (!endAt) return false;
      const endDate = new Date(endAt);
      const now = new Date();
      return endDate < now;
    },
  },
};
</script>

<style scoped>
/* 样式保持不变 */
.delivered-page {
  padding: 20px;
  min-height: calc(100vh - 40px);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}
.search-container {
  display: flex;
  align-items: center;
}

.user-info {
  display: flex;
  align-items: center;
  padding: 5px 0;
}

.avatar {
  border: 1px solid #eee;
}

.user-info-detail {
  margin-left: 10px;
}

.name {
  font-weight: 500;
  margin-bottom: 5px;
}

.phone {
  color: #606266;
  font-size: 13px;
}

.expected-item {
  margin-bottom: 4px;
  font-size: 13px;
}

.position-name {
  display: flex;
  align-items: center;
  gap: 5px;
  font-weight: 500;
  margin-bottom: 5px;
}

.time-item {
  font-size: 13px;
  margin-bottom: 3px;
}

.expired {
  color: #909399;
}

.disabled-btn {
  background-color: #f5f7fa;
  border-color: #e4e7ed;
  color: #c0c4cc;
  cursor: not-allowed;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.section-title {
  margin: 0 0 10px 0;
  font-size: 16px;
  color: #303133;
  padding-bottom: 5px;
  border-bottom: 1px dashed #e4e7ed;
}

.section-content {
  padding-left: 5px;
}

.content-row {
  margin-bottom: 8px;
  font-size: 14px;
}

.content-label {
  display: inline-block;
  width: 100px;
  color: #909399;
}

.text-danger {
  color: #f56c6c;
}
</style>